using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MsgBackend.Api.Models;
using MsgBackend.Api.ParamModel;
using MsgBackend.Api.Repository;

namespace MsgBackend.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class RecordReadController : ControllerBase
    {
        private IRepository<RecordRead> _recordReadRepository;

        private IRepository<Articles> _articlesRepository;

        private TokenParamter _tokenparamter;

        private readonly IConfiguration _configuration;

        public RecordReadController(
            IRepository<Articles> articlesRepository,
            IRepository<RecordRead> recordReadRepository,
            IConfiguration configuration
        )
        {
            _configuration = configuration;
            _recordReadRepository = recordReadRepository;
            _articlesRepository = articlesRepository;
            _tokenparamter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParamter>();
        }

        //添加阅读量
        [HttpPost]
        public ActionResult AddRead(ParamRead model)
        {
            var recordRead =
                new RecordRead { UsersId = 1, ArticlesId = model.ArticlesId };

            _recordReadRepository.Insert (recordRead);

            return Ok(new { Code = 1000, Data = recordRead, Msg = "添加成功" });
        }

        //阅读排行榜
        [HttpGet("readTop")]
        public ActionResult ReadTop()
        {
            var reads = _recordReadRepository.Table.ToList();
            var articles = _articlesRepository.Table.ToList();
            var article = articles.Where(x =>x.IsActived==true).ToList();
            var readTop =
                (
                from top
                in
                (
                from top in reads
                group top by top.ArticlesId
                into g select new { ArticlesId = g.Key, cnt = g.Count() }
                )
                join Name in article
                on top.ArticlesId equals Name.Id
                orderby top.cnt descending
                select new { top.ArticlesId, top.cnt,Name.ArticleName }
                ).Take(5).ToList();

            return Ok(new { Data = readTop });
        }

        //根据文章id获取阅读数
        [HttpGet("read/{id}")]
        public ActionResult ReadCount(int id)
        {
            var articles = _recordReadRepository.Table;
            var article = articles.Where(x => x.ArticlesId == id).Count();
            return Ok(new
            {
                Code = 1000,
                Data = article,
                Msg = "获得成功"
            });
        }
    }
}
